package com.zhu.blog.controller;



import com.zhu.blog.model.Message;
import com.zhu.blog.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Value("${comment.avatar}")
    private String avatar;

    @Value("${admin.openid}")
    private String adminOpenid;

    //展示留言列表
    @RequestMapping(value = "/Messages",method = RequestMethod.GET)
    public String Message_board(@PageableDefault(size = 6,sort = {"createTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, Model model){
        model.addAttribute("messages",messageService.listMessage(pageable));
        return "message_board";
    }

    //前端ajax发送请求到后台提交数据到数据库
    @PostMapping("/postMessages")
    public String post(Message message, HttpSession session){
        String loginStatus = (String) session.getAttribute("loginStatus");
        //判断是否访客评论
        if(loginStatus != null){
            String openid = (String) session.getAttribute("openid");//qq标识
            String avatar = (String) session.getAttribute("avatar");
            String node_id = (String) session.getAttribute("node_id");//GitHub标识
            message.setAvatar(avatar);
            message.setAdminMessage(1);
            //判断是否GitHub用户评论
            if(StringUtils.isNotBlank(node_id)){
                message.setAdminMessage(3);
            }
            //判断是否博主评论
            if(adminOpenid.equals(openid)){
                message.setAdminMessage(2);
            }
        }else {
            message.setAdminMessage(0);
            message.setAvatar(avatar);
        }
        messageService.saveMessage(message);
        messageService.findParentMessage(message);
        return "redirect:/Message";
    }

    //将数据返回message_board页面的th:fragment="messageList"片段，实现局部刷新
    @RequestMapping(value = "/Message",method = RequestMethod.GET)
    public String Message(@PageableDefault(size = 6,sort = {"createTime"},direction = Sort.Direction.DESC)
                          Pageable pageable, Model model){
        model.addAttribute("messages",messageService.listMessage(pageable));
        return "message_board :: messageList";
    }
}
